<?php

namespace App\Http\Controllers\Admin\Wechat\Manager\Material;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use Validator;
use Log;
use DB;

use App\Models\Wechat\Mpnews;

class MpnewsController extends AdminController
{
    /**
     * 获取列表
     * @return [type] [description]
     */
    function getLists(Request $request){
        $size = $request->input('size');
        $where  = [] ;
        $page   = $request->input('page') ? $request->input('page') : 1;
        $start  = ($page-1)*$size;
        $total = Mpnews::where($where)->count();

        $list['total'] = $total;
        if($total>0){
            $mpnews = Mpnews::where($where)->orderBy('created_at','desc')->skip($start)->take($size)->get();
            foreach ($mpnews as $mpnew) {
                $wechat_news_ids = trim($mpnew->wechat_news_ids,',');
                $mpnew->news = DB::select("select * from wechat_news where id in ($wechat_news_ids) ORDER BY field(id,$wechat_news_ids)");
            }
            $list['list'] = $mpnews;
        }
        $this->ajaxJson(0,'',$list);
    }

    /**
     * 获取单个图文消息
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function getOne($id){
        $mpnews = $this->_get_one($id);
        $wechat_news_ids = trim($mpnews->wechat_news_ids,',');
        $news = DB::select("select * from wechat_news where id in ($wechat_news_ids) ORDER BY field(id,$wechat_news_ids)");
        $this->ajaxJson(0,'',$news);
    }

	/**
	 * 更新图文消息
	 * @return [type] [description]
	 */
    function updateMpnews(Request $request){
        $mpnewsModel = new Mpnews();
    	$mpnews = $request->input('mpnews');
    	$mpnews_id = $request->input('mpnews_id');
    	foreach ($mpnews as $data) {
    		$validator = $this->formValidator($data);
            if($validator->fails()){
                $this->ajaxJson(1,$validator->errors()->first());
            }
    	}
    	$idstr = '';
    	try {
    		DB::beginTransaction();
    		foreach ($mpnews as $data) {
    			$format = [
						'title'      => $data['title'],
                        'desc'      => $data['desc'],
						'pic'        => $data['pic'],
						'originPic'  => $data['originPic'],
						'link'       => $data['link'],
						'created_at' => date('Y-m-d H:i:s'),
						'updated_at' => date('Y-m-d H:i:s'),
	    			];

	    		if($data['id']){
	    			$idstr .= $data['id'].',';
	    			$news = DB::table('wechat_news')->find($data['id']);
	    			if(!$news){
	    				$this->ajaxJson(1,'更新了不存在的图文消息');
	    			}
	    			$format['updated_at'] = date('Y-m-d H:i:s');
	    			DB::table('wechat_news')->where('id',$data['id'])->update($format);
	    		}else{
	    			$id = DB::table('wechat_news')->insertGetId($format);
	    			$idstr .= $id.',';
	    		}
	    		unset($format);
	    	}
	    	$mpnewsFormat = [
	    		'wechat_news_ids' => $idstr,
	    		'created_at' => date('Y-m-d H:i:s'),
	    		'updated_at' => date('Y-m-d H:i:s'),
	    	];
	    	if($mpnews_id){
	    		$mpnewsFormat['updated_at'] = date('Y-m-d H:i:s');
	    		DB::table('wechat_mpnews')->where('id',$mpnews_id)->update($mpnewsFormat);
	    	}else{
	    		DB::table('wechat_mpnews')->insert($mpnewsFormat);
	    	}
            $mpnewsModel->cacheEmpty($mpnews_id);
	    	DB::commit();
	    	$this->ajaxJson(0,'发布成功');
    	} catch (Exception $e) {
    		DB::rollBack();
    		Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
    		$this->ajaxJson(1,'发布图文消息失败');
    	}
    	
    }

    /**
     * 删除单条图文
     * @return [type] [description]
     */
    function deleteOne($id){
        DB::beginTransaction();
        try {
            $mpnews = $this->_get_one($id);
            DB::table('wechat_mpnews')->where('id',$id)->delete();
            DB::table('wechat_news')->whereIn('id',explode(',', trim($mpnews->wechat_news_ids,',')))->delete();
            $mpnews->cacheEmpty($id);
            DB::commit();
            $this->ajaxJson(0,'删除成功');
        } catch (Exception $e) {
            DB::rollBack();
            $this->ajaxJson(1,'删除失败');
        }
    }

    /**
     * 删除图文消息中的一条图文
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function deleteNews(Request $request){
        $news_id = $request->input('news_id');
        $mpnews_id = $request->input('mpnews_id');
        $mpnews = $this->_get_one($mpnews_id);
        DB::beginTransaction();
        try {
            DB::table('wechat_news')->where('id',$news_id)->delete();
            $wechat_news_ids = str_replace($news_id.',', '', $mpnews->wechat_news_ids) ;
            DB::table('wechat_mpnews')->where('id',$mpnews_id)->update([
                'wechat_news_ids' => $wechat_news_ids,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            $mpnews->cacheEmpty($mpnews_id);
            DB::commit();
            $this->ajaxJson(0,'删除成功');
        } catch (Exception $e) {
            DB::rollBack();
            $this->ajaxJson(1,'删除失败');
        }
    }

    /**
     * 表单验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
            'title' => '图文标题',
            'pic' => '封面',
            'link' => '链接地址',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'url' => ':attribute 网址错误',
        );

        return Validator::make($data, [
            'title' => 'bail|required',
            'pic' => 'bail|required',
            'link' => 'bail|required|url',
        ],$message,$attribute);
    }

    /**
     * 获取单条
     * @return [type] [description]
     */
    private function _get_one($id){
        $mpnews = Mpnews::find($id);
        if(!$mpnews){
            $this->ajaxJson(1,'未知数据');
        }
        return $mpnews;
    }
}
